package com.giscloud.amp.service.auth.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.giscloud.amp.dao.AmpOrgMapper;
import com.giscloud.amp.dao.AmpStaffOrgMapper;
import com.giscloud.amp.entity.AmpStaffOrg;
import com.giscloud.amp.entity.AmpStaffOrgExample;
import com.giscloud.amp.entity.dto.AmpOrgDTO;
import com.giscloud.amp.entity.dto.AmpStaffOrgDTO;
import com.giscloud.amp.entity.vo.AmpOrgTreeVO;
import com.giscloud.amp.entity.vo.AmpStaffOrgVO;
import com.giscloud.amp.entity.vo.AmpStaffSystemOrgVO;
import com.giscloud.amp.service.auth.AmpStaffOrgService;
import com.giscloud.datasource.page.PageInfo;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author:gxd
 * @Description:
 * @Date: 11:04 2018/2/24
 * @Modified By:
 */
@Service("ampStaffOrgService")
@CacheConfig(cacheNames ="amp:ampStaffOrgService")
public class AmpStaffOrgServiceImpl implements AmpStaffOrgService {

    private final static Logger log = LoggerFactory.getLogger(AmpStaffOrgServiceImpl.class);
    @Autowired
    private AmpStaffOrgMapper ampStaffOrgMapper;
    @Autowired
    private AmpOrgMapper ampOrgMapper;

    @Override
    public PageInfo getAmpStaffOrgList(AmpStaffOrgDTO ampStaffOrgDTO) {
        log.debug("#getAmpStaffOrgList parameter ={}", JSON.toJSONString(ampStaffOrgDTO));
        PageHelper.startPage(ampStaffOrgDTO.getPage(), ampStaffOrgDTO.getRows());
        AmpStaffOrgExample ampStaffOrgExample = new AmpStaffOrgExample();
        AmpStaffOrgExample.Criteria criteria = ampStaffOrgExample.createCriteria();
        List<AmpStaffOrgVO> ampStaffOrgs = ampStaffOrgMapper.selectByExample(ampStaffOrgExample);
        return PageInfo.of(ampStaffOrgs);
    }
    @Override
    public AmpStaffOrgVO getAmpStaffOrgByCondition(AmpStaffOrgDTO ampStaffOrgDTO) {
        log.debug("#getAmpStaffOrgByCondition parameter ={}", JSON.toJSONString(ampStaffOrgDTO));
        AmpStaffOrgExample ampStaffOrgExample = new AmpStaffOrgExample();
        AmpStaffOrgExample.Criteria criteria = ampStaffOrgExample.createCriteria();

        List<AmpStaffOrgVO> ampStaffOrgs = ampStaffOrgMapper.selectByExample(ampStaffOrgExample);
        if(!CollectionUtil.isEmpty(ampStaffOrgs) && ampStaffOrgs.size() == 1){
            return ampStaffOrgs.get(0);
        }else{
            return  null;
        }
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public int insert(AmpStaffOrgDTO ampStaffOrgDTO) {
            //插入前，先删除
            //根据当前系统id 获取orgId
            AmpOrgDTO ampOrgDTO = new AmpOrgDTO();
            ampOrgDTO.setSystemId(ampStaffOrgDTO.getSystemId());
            List<AmpOrgTreeVO> ampOrgTree = ampOrgMapper.findAmpOrgTree(ampOrgDTO);

            AmpStaffOrgExample ampStaffOrgExample = new AmpStaffOrgExample();
            AmpStaffOrgExample.Criteria criteria = ampStaffOrgExample.createCriteria();
            if(ampStaffOrgDTO.getStaffId() != null){
                criteria.andStaffIdEqualTo(ampStaffOrgDTO.getStaffId());
            }
            List<Long> list = ampOrgTree.stream()
                    .map(s -> s.getOrgId()).collect(Collectors.toList());
            criteria.andOrgIdIn(list);
            AmpStaffOrg ampStaffOrg = new AmpStaffOrg();
            ampStaffOrg.setStatusCd((short) 2);
            ampStaffOrg.setOpreateStaffId(ampStaffOrgDTO.getOpreateStaffId());
            ampStaffOrg.setVersion(new Date());
            ampStaffOrgMapper.updateByExampleSelective(ampStaffOrg,ampStaffOrgExample);
            if(StringUtils.isNotBlank(ampStaffOrgDTO.getOrgIds())) {
                String[] orgIds = ampStaffOrgDTO.getOrgIds().split("@");
                //批量插入部门
                for (String orgId : orgIds) {
                    ampStaffOrg = new AmpStaffOrg();
                    BeanUtils.copyProperties(ampStaffOrgDTO, ampStaffOrg);
                    ampStaffOrg.setStatusCd((short) 1);
                    ampStaffOrg.setCreatedDt(new Date());
                    ampStaffOrg.setVersion(new Date());
                    ampStaffOrg.setOrgId(Long.valueOf(orgId));
                    ampStaffOrgMapper.insert(ampStaffOrg);
                }
            }
        return 1;
    }
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    public int update(AmpStaffOrgDTO ampStaffOrgDTO) {
        AmpStaffOrgExample ampStaffOrgExample = new AmpStaffOrgExample();
        AmpStaffOrgExample.Criteria criteria = ampStaffOrgExample.createCriteria();
        if(ampStaffOrgDTO.getStaffId() != null){
            criteria.andStaffIdEqualTo(ampStaffOrgDTO.getStaffId());
        }
        if(ampStaffOrgDTO.getRelId() != null){
            criteria.andRelIdEqualTo(ampStaffOrgDTO.getRelId());
        }
        AmpStaffOrg ampStaffOrg = new AmpStaffOrg();
        BeanUtils.copyProperties(ampStaffOrgDTO,ampStaffOrg);
        ampStaffOrg.setVersion(new Date());
        ampStaffOrg.setStatusCd(ampStaffOrgDTO.getStatusCd());
        return ampStaffOrgMapper.updateByExample(ampStaffOrg,ampStaffOrgExample);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class)
    @CacheEvict(cacheNames = {"amp:ampStaffService"}, allEntries = true)
    public int delete(Long relId) {
        AmpStaffOrgExample ampStaffOrgExample = new AmpStaffOrgExample();
        AmpStaffOrgExample.Criteria criteria = ampStaffOrgExample.createCriteria();
        if(relId != null){
            criteria.andRelIdEqualTo(relId);
        }
        return ampStaffOrgMapper.deleteByExample(ampStaffOrgExample);
    }

    @Override
    public Set<String> getOrgCodeByCondition(String staffId) {
        Set<String> roleCode = new HashSet<>();
        AmpStaffOrgExample ampStaffOrgExample = new AmpStaffOrgExample();
        AmpStaffOrgExample.Criteria criteria = ampStaffOrgExample.createCriteria();
        criteria.andStatusCdEqualTo((short)1);
        List<AmpStaffOrgVO> ampStaffOrgs = ampStaffOrgMapper.selectByExample(ampStaffOrgExample);

        for (AmpStaffOrgVO ampStaffOrg : ampStaffOrgs) {
            roleCode.add(String.valueOf(ampStaffOrg.getOrgId()));
        }
        return roleCode;
    }

    @Override
    @Cacheable(key= "'amp:dataauth:getOrgByStaffId:'+T(com.alibaba.fastjson.JSON).toJSONString('staffId:'+#ampStaffOrgDTO.staffId+':systemId:'+#ampStaffOrgDTO.systemId+':orgId:'+#ampStaffOrgDTO.orgId)",unless="#result.size() == 0")
    public List<AmpStaffSystemOrgVO> getOrgByStaffId(AmpStaffOrgDTO ampStaffOrgDTO) {
        return ampStaffOrgMapper.getOrgByStaffId(ampStaffOrgDTO);
    }
}
